package baiqitun.netfiles.listener;

import baiqitun.netfiles.config.properties.NetFilesProperties;
import baiqitun.netfiles.config.properties.RootProperties;
import baiqitun.netfiles.entity.SysDirectory;
import baiqitun.netfiles.service.SysDirectoryService;
import cn.hutool.core.util.IdUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.LinkedList;
import java.util.List;

@Order(Integer.MIN_VALUE + 10)
@Component
public class AreaInitApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private NetFilesProperties netFilesProperties;
    @Autowired
    private SysDirectoryService sysDirectoryService;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        List<SysDirectory> roots = new LinkedList<>();
        for (RootProperties rootProperties: netFilesProperties.getRoot()) {
            String path = rootProperties.getPath();
            if (Files.exists(Paths.get(path))){
                SysDirectory root = new SysDirectory();
                String id = IdUtil.fastSimpleUUID();
                root.setId(id);
                root.setRootId(id);
                root.setName(rootProperties.getAlias());

                sysDirectoryService.save(rootProperties.getPath(), root);
                roots.add(root);
            }
        }
        sysDirectoryService.saveObject(sysDirectoryService.formatKey("roots"), roots);
    }
}
